package com.begamer.card.model.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.begamer.card.common.util.binRead.ItemsData;
import com.begamer.card.model.pojo.Card;
import com.begamer.card.model.pojo.Equip;
import com.begamer.card.model.pojo.Item;
import com.begamer.card.model.pojo.PassiveSkill;
import com.begamer.card.model.pojo.PkRank;
import com.begamer.card.model.pojo.Player;
import com.begamer.card.model.pojo.Skill;

public class GmPlayerDao extends HibernateDaoSupport {

	// @SuppressWarnings("unchecked")

	private Player player;


	/***************************************************************************
	 * 分页查询
	 * 
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Player> getAllByPage(final int currentPage, final int pageSize)
	{

		return this.getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException
			{

				Query query = session.createQuery("from Player p where p.userId>0");
				query.setMaxResults(pageSize);
				query.setFirstResult((currentPage - 1) * pageSize);
				return query.list();
			}

		});
	}

	@SuppressWarnings("unchecked")
	public List<Player> findAllPlayer() throws Exception
	{

		Session session = getSession();
		try
		{
			String hql = "from Player p where p.userId>0";
			Query query = session.createQuery(hql);
			List<Player> players = query.list();
			return players;
		}
		catch (RuntimeException er)
		{
			throw er;
		}
		finally
		{
			session.close();
		}

	}

	public Player getOneByP_id(int p_id)
	{

		Session session = getSession();
		try
		{
			String hql = "from Player p where p.id=? and p.userId>0";
			Query query = session.createQuery(hql);
			query.setInteger(0, p_id);
			player = (Player) query.uniqueResult();
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}

		return player;
	}

	@SuppressWarnings("unchecked")
	public void updatePlayer(Player player)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			Query query2=session.createQuery("from Player p where p.id=?");
			query2.setInteger(0, player.getId());
			List<Player> pList=query2.list();
			String platform=null;
			if(pList!=null && pList.size()>0)
			{
				platform=pList.get(0).getPlatform();
			}
			player.setPlatform(platform);
			player.updateVipLevel();
			
			String hql = "update Player p set p.level=?,p.power=?,p.gold=?,p.crystal=?,p.crystalPay=?,p.kopoint=?,p.vipCost=?,p.runeNum=?,p.vipLevel=?,p.diamond=?,p.pvpHonor=? where p.id=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, player.getLevel());
			query.setInteger(1, player.getPower());
			query.setInteger(2, player.getGold());
			query.setInteger(3, player.getCrystal());
			query.setInteger(4, player.getCrystalPay());
			query.setInteger(5, player.getKopoint());
			query.setInteger(6, player.getVipCost());
			query.setInteger(7, player.getRuneNum());
			query.setInteger(8, player.getVipLevel());
			query.setInteger(9, player.getDiamond());
			query.setInteger(10, player.getPvpHonor());
			query.setInteger(11, player.getId());
			query.executeUpdate();
			ts.commit();
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}
	
	public void upNewPlayer(int p_id)
	{
		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			Query query = session.createQuery("update Player p set p.newPlayerType=100 where p.id=?");
			query.setInteger(0, p_id);
			query.executeUpdate();
			ts.commit();
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Item> getItemByPlayerId(int p_id)
	{

		Session session = getSession();
		try
		{
			String hql = "from Item t where t.playerId=? and t.sell=0";
			Query q = session.createQuery(hql);
			q.setInteger(0, p_id);
			List<Item> list = q.list();
			return list;
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}

	}

	public void updateItem(Item item)
	{

		Session session = this.getSession();
		try
		{
			String hql = "update Item t set t.pile=? where t.playerId=? and t.itemId=?";
			Query q = session.createQuery(hql);
			q.setInteger(0, item.getPile());
			q.setInteger(1, item.getPlayerId());
			q.setInteger(2, item.getItemId());
			q.executeUpdate();
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}

	}

	@SuppressWarnings("unchecked")
	public List<Item> getItemByI_idAndP_id(int I_id, int p_id)
	{

		Session session = getSession();
		try
		{
			String hql = "from Item t where t.itemId=? and t.playerId=? and t.sell=0";
			Query q = session.createQuery(hql);
			q.setInteger(0, I_id);
			q.setInteger(1, p_id);
			return q.list();
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}

	}

	public void addItemByPlayerId(Item item)
	{
		Session session = getSession();
		try
		{
			List<Item> list = getItemByI_idAndP_id(item.getItemId(), item.getPlayerId());
			ItemsData itemsData = ItemsData.getItemsData(item.getItemId());
			if (list != null && list.size()>0)
			{
				boolean is = true;
				for (Item it : list)
				{
					if (it.getPile()!=itemsData.pile)
					{
						is = false;
						if (it.getPile() + item.getPile() > itemsData.pile) {
							Query q1 = session.createQuery("update Item i set i.pile=? where i.id=?");
							q1.setInteger(0, itemsData.pile);
							q1.setInteger(1, it.getId());
							q1.executeUpdate();
							int num1 = (item.getPile()+it.getPile()) - itemsData.pile;
							if (num1>itemsData.pile)
							{
								int num = 0;
								for (int i = 1; i <= (float)num1/itemsData.pile; i++)
								{
									num = num1 - i*itemsData.pile;
									item.setPile(itemsData.pile);
									getHibernateTemplate().save(item);
								}
								item.setPile(num);
								getHibernateTemplate().save(item);
							}
							else
							{
								item.setPile(num1);
								getHibernateTemplate().save(item);
							}
						}
						else 
						{
							int num = it.getPile() + item.getPile();
							Query q1 = session.createQuery("update Item i set i.pile=? where i.id=?");
							q1.setInteger(0, num);
							q1.setInteger(1, it.getId());
							q1.executeUpdate();
						}
					}
				}
				if (is)
				{
					if (item.getPile()>itemsData.pile)
					{
						int num1 = item.getPile();
						int num = 0;
						for (int i = 1; i <= (float)num1/itemsData.pile; i++)
						{
							num = num1 - i*itemsData.pile;
							item.setPile(itemsData.pile);
							getHibernateTemplate().save(item);
						}
						item.setPile(num);
						getHibernateTemplate().save(item);
					}
					else
					{
						getHibernateTemplate().save(item);
					}
				}
			}
			else
			{
				if (item.getPile()>itemsData.pile)
				{
					int num1 = item.getPile();
					int num = 0;
					for (int i = 1; i <= (float)num1/itemsData.pile; i++)
					{
						num = num1 - i*itemsData.pile;
						item.setPile(itemsData.pile);
						getHibernateTemplate().save(item);
					}
					item.setPile(num);
					getHibernateTemplate().save(item);
				}
				else
				{
					getHibernateTemplate().save(item);
				}
			}
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Card> getCardByP_id(int p_id)
	{

		Session session = getSession();
		try
		{
			String hql = "from Card c where c.playerId=? and c.sell=0";
			Query q = session.createQuery(hql);
			q.setInteger(0, p_id);
			List<Card> list = q.list();
			return list;
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Equip> getEquipByP_id(int p_id)
	{

		Session session = getSession();
		try
		{
			String hql = "from Equip e where e.playerId=? and e.sell=0";
			Query q = session.createQuery(hql);
			q.setInteger(0, p_id);
			List<Equip> list = q.list();
			return list;
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<PassiveSkill> getPassiveSkillByP_id(int p_id)
	{

		Session session = getSession();
		try
		{
			String hql = "from PassiveSkill p where p.playerId=? and p.sell=0";
			Query q = session.createQuery(hql);
			q.setInteger(0, p_id);
			List<PassiveSkill> list = q.list();
			return list;
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Skill> getSkillByP_id(int p_id)
	{

		Session session = getSession();
		try
		{
			String hql = "from Skill s where s.playerId=? and s.sell=0";
			Query q = session.createQuery(hql);
			q.setInteger(0, p_id);
			List<Skill> list = q.list();
			return list;
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	public PkRank getPkRankByP_id(int p_id)
	{

		Session session = getSession();
		try
		{
			Query q = session.createQuery("from PkRank pk where pk.playerId=?");
			q.setInteger(0, p_id);
			PkRank pkrank = (PkRank) q.uniqueResult();
			return pkrank;
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	public void upfbFight(Player player)
	{

		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			String hql = "update Player p set p.FBnum1=? where p.id=?";
			Query query = session.createQuery(hql);
			query.setString(0, player.getFBnum1());
			query.setInteger(1, player.getId());
			query.executeUpdate();
			ts.commit();
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	public void upmazeFight(Player player)
	{

		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			String hql = "update Player p set p.maze=? where p.id=?";
			Query query = session.createQuery(hql);
			query.setString(0, player.getMaze());
			query.setInteger(1, player.getId());
			query.executeUpdate();
			ts.commit();
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	public void upmissionFight(Player player)
	{

		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			String hql = "update Player p set p.missionId=? where p.id=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, player.getMissionId());
			query.setInteger(1, player.getId());
			query.executeUpdate();
			ts.commit();
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	public void uppvpFight(PkRank pkrank)
	{

		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			String hql = "update PkRank pk set pk.pkNum=? where pk.playerId=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, pkrank.getPkNum());
			query.setInteger(1, pkrank.getPlayerId());
			query.executeUpdate();
			ts.commit();
		}
		catch (RuntimeException re)
		{
			throw re;
		}
		finally
		{
			session.close();
		}
	}

	public void addCard(Card card)
	{

		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.save(card);
			ts.commit();
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}

	public void addEquip(Equip equip)
	{

		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.save(equip);
			ts.commit();
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}

	public void addPassiveSkill(PassiveSkill passiveSkill)
	{

		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.save(passiveSkill);
			ts.commit();
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}

	public void addSkill(Skill skill)
	{

		Session session = getSession();
		Transaction ts = session.beginTransaction();
		try
		{
			session.save(skill);
			ts.commit();

		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}

	/** *****分页模糊查询，根据角色名称**** */
	@SuppressWarnings("unchecked")
	public List<Player> mhP_name(final int currentPage, final int pageSize,
			final String name)
	{

		return this.getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException
			{

				String hql = "from Player p where p.name like '%" + name + "%' and p.userId>0";
				Query query = session.createQuery(hql);
				query.setMaxResults(pageSize);
				query.setFirstResult((currentPage - 1) * pageSize);
				List<Player> list = query.list();
				return list;
			}

		});
	}

	// ** *****模糊查询，根据角色名称**** *//*
	@SuppressWarnings("unchecked")
	public List<Player> mhP_name(String name)
	{

		Session session = getSession();
		try
		{
			String hql = "from Player p where p.name like '%" + name + "%' and p.userId>0";
			Query query = session.createQuery(hql);
			List<Player> list = query.list();
			return list;
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}

	}
	/** *****分页根据角色名称精确查询**** */
	@SuppressWarnings("unchecked")
	public List<Player> getPlayerByPName(final int currentPage, final int pageSize,
			final String name)
	{

		return this.getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException
			{

				String hql = "from Player p where p.name=? and p.userId>0";
				Query query = session.createQuery(hql);
				query.setString(0, name);
				query.setMaxResults(pageSize);
				query.setFirstResult((currentPage - 1) * pageSize);
				List<Player> list = query.list();
				return list;
			}

		});
	}
	/**根据角色名称精确查询**/
	@SuppressWarnings("unchecked")
	public List<Player> getPlayerByPName(String name)
	{
		Session session = getSession();
		try
		{
			String hql = "from Player p where p.name=? and p.userId>0";
			Query query = session.createQuery(hql);
			query.setString(0, name);
			List<Player> list = query.list();
			return list;
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}
	/** 统计注册玩家数* */
	public int getUserNum()
	{
		Session session = getSession();
		try
		{
			Query query = session.createQuery("select count(id) from User");
			return Integer.parseInt(query.uniqueResult().toString()) ;
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}
	/**查看等级N以上玩家**/
	@SuppressWarnings("unchecked")
	public List<Player> getPlayerByPLevel(int level)
	{
		Session session = getSession();
		try
		{
			Query query = session.createQuery("from Player p where p.level>=? and p.userId>0 order by p.level desc");
			query.setInteger(0, level);
			return query.list();
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}
	/**分页查询查看等级N以上玩家**/
	@SuppressWarnings("unchecked")
	public List<Player> getPlayerByPLevelByPage(final int currentPage, final int pageSize,final int level)
	{

		return this.getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException
			{

				Query query = session.createQuery("from Player p where p.level>=? and p.userId>0 order by p.level desc");
				query.setMaxResults(pageSize);
				query.setFirstResult((currentPage - 1) * pageSize);
				query.setInteger(0, level);
				return query.list();
			}

		});
	}
	/**查询vip经验N以上的玩家**/
	@SuppressWarnings("unchecked")
	public List<Player> getPlayerByPvipCost(int vipCost)
	{
		Session session = getSession();
		try
		{
			Query query = session.createQuery("from Player p where p.vipCost>=? and p.userId>0");
			query.setInteger(0, vipCost);
			return query.list();
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}
	/**分页查询vip经验N以上的玩家**/
	@SuppressWarnings("unchecked")
	public List<Player> getPlayerByPvipCost(final int currentPage, final int pageSize,final int level)
	{

		return this.getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException
			{

				Query query = session.createQuery("from Player p where p.vipCost>=? and p.userId>0");
				query.setMaxResults(pageSize);
				query.setFirstResult((currentPage - 1) * pageSize);
				query.setInteger(0, level);
				return query.list();
			}

		});
	}
}
